#!/usr/bin/perl
# farsail_run --- 
# Author: Ye Wenbin <wenbinye@gmail.com>
# Created: 24 Nov 2008
# Version: 0.01

use warnings;
use strict;
use FindBin qw/$Bin/;
use lib "$Bin/lib", "$Bin/../lib";
use Log::Log4perl;
use Farsail;

my $farsail = Farsail->instance;

$farsail->init();

if ( check_init() ) {
    $farsail->dispatch();
}

sub check_init {
    my $action = $farsail->current_action;
    if ( !defined $action ) {
        die "No action! Use `$0 help` to find some help.\n"
    }
    if ( $action eq 'help' ) {
        return 1;
    }
    # setup log4perl
    my $config = $farsail->config;
    if ( $farsail->args->cron && $action =~ /\b(daily|weekly|monthly)\b/ ) {
        my $new_logger = ucfirst($1);
        my @logger = split /\s*,\s*/, $config->get('log4perl.logger');
        $config->set('log4perl.logger',
                     join(",", (grep {$_ ne 'File'} @logger), $new_logger));
    }
    ### FIXME: init Log::Log4perl will change $SIG{__DIE__}, I can't find which module change it.
    Log::Log4perl->init(\$config->log4perl);
    # make fake take affect
    if ( $farsail->args->fake ) {
        require Farsail::Mock;
        Farsail::Mock->import(qw/DBI PBS open system/);
        $farsail->logger(Log::Log4perl->get_logger);
    } else {
        require Farsail::EventLog;
        $farsail->logger( 'Farsail::EventLog' );
    }
    # install signal handler
    $SIG{__DIE__} = sub {
        if ( $^S ) {
            return;
        }
        my $logger = Log::Log4perl->get_logger;
        my $msg = join('', @_);
        my $current_action = $farsail->current_action;
        $farsail->log($action, 'ERROR');
        my $title = "Perform $current_action failed";
        if ( $farsail->args->cron ) {
            my $pager = $farsail->config->get('admin.pager');
            $logger->info("mail to $pager");
            if ( $pager ) {
                open(my $fh, "| mail -s '$title' $pager")
                    or $logger->fatal("Can't send mail\n");
                print {$fh} $msg;
                close $fh;
            }
        }
        $logger->logdie("$title:\n", $msg);
    };
    $farsail->log('FARSAIL', 'START', join(" ", $$, @ARGV));
}

END {
    $farsail->log('FARSAIL', 'END', $$);
}
